﻿using Elsa.Services;
using Zhp.Workflow.Activities;
using Zhp.Workflow.Models;

namespace Zhp.Workflow
{
    public class ApproveBookmarkProvider : BookmarkProvider<ApproveBookmark, ApproveActivity>
    {
        public override async ValueTask<IEnumerable<BookmarkResult>> GetBookmarksAsync(BookmarkProviderContext<ApproveActivity> context, CancellationToken cancellationToken)
        {
            var userinfo = (await context.ReadActivityPropertyAsync<ApproveActivity, ICollection<string>>(x => x.ApproveUsers, cancellationToken))?.ToList() ?? new List<string>();
            var roleinfo = (await context.ReadActivityPropertyAsync<ApproveActivity, ICollection<string>>(x => x.ApproveRoles, cancellationToken))?.ToList() ?? new List<string>();
            var tag = await context.ReadActivityPropertyAsync<ApproveActivity, string>(x => x.Tag, cancellationToken);
            var name = context.ActivityExecutionContext.WorkflowExecutionContext.WorkflowBlueprint.Name ?? "";
            var model = context.ActivityExecutionContext.WorkflowExecutionContext.WorkflowBlueprint.ContextOptions?.ContextType?.FullName;
            var id = context.ActivityExecutionContext.WorkflowExecutionContext.ContextId?.ToString() ?? "";
            
            List<BookmarkResult> rv = new List<BookmarkResult>();
            if (userinfo?.Any() == true)
            {
                rv.AddRange(userinfo.Select(x => Result(new ApproveBookmark(x, name, tag, id))));
            }
            if (roleinfo?.Any() == true)
            {
                rv.AddRange(roleinfo.Select(x => Result(new ApproveBookmark(x, name, tag, id))));
            }
            if (rv.Count > 0)
            {
                return rv;
            }
            return new BookmarkResult[0];
        }
    }
}
